# -*- coding:utf-8 -*-
import os
import pprint
import string
import random
from datetime import datetime
# import cx_Oracle
import requests
import json
import jsonpath
import configparser
import yaml
import pymysql
import time


class keyWords():

    def do_get(self, url, **kwargs):
        res = requests.get(url=url, **kwargs)
        print(res.text)
        return res

    def do_post(self, url, **kwargs):
        res = requests.post(url=url, **kwargs)
        print(res.text)
        return res

    # 获取接口返回值中的某个值
    def get_value(self,txt,value):
        txt = json.loads(txt)
        value = jsonpath.jsonpath(txt,'$..{}'.format(value))
        if value:
            if len(value) == 1:
                return value[0]
            return value

    # 读取ini类型配置文件中的值
    def read_ini(self,path,section,option):
        conf = configparser.ConfigParser()
        conf.read(path,encoding='utf-8')
        value = conf.get(section,option)
        return value

    # 读取yaml格式的值
    def read_yaml(self,path):
        with open(path, 'r', encoding='utf-8') as f:
            data = yaml.load(f, yaml.FullLoader)
            return data

    def update_yaml(self,path, key, value):
        with open(path, 'r', encoding='utf-8') as f:
            lines = []  
            for line in f.readlines():
                if line != '\n':
                    lines.append(line)
            f.close()
        with open(path, 'w', encoding='utf-8') as f:
            flag = 0
            for line in lines:
                if key in line and '#' and '$' not in line:
                    leftstr = line.split(":")[0]
                    newline = "{0}: {1}".format(leftstr, value)
                    line = newline
                    f.write('%s\n' % line)
                    flag = 1
                else:
                    f.write('%s' % line)
            f.close()
            return flag


    #获取当前调用时所在文件夹的绝对路径
    def current_dir(self,file):
        path = os.path.dirname(file)
        return path

    #获取当前调用时所在文件夹的上一层文件夹绝对路径
    def upper_dir(self,file):
        path = os.path.dirname(os.path.dirname(file))
        return path


    # # 数据库查询
    # def Oracle_select(self,connectInfo,sql):
    #     os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
    #     db = cx_Oracle.connect(connectInfo)
    #     cursor = db.cursor()
    #     cursor.execute(sql)
    #     row = cursor.fetchone()
    #     print(row)
    #     cursor.close()
    #     db.close()
    #     return row

    # # 数据库增/删/改
    # def Oracle_update(self,connectInfo,sql):
    #     os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
    #     db = cx_Oracle.connect(connectInfo)
    #     cursor = db.cursor()
    #     cursor.execute('BEGIN ' + sql + ' END;')
    #     # cursor.executemany()
    #     db.commit()
    #     cursor.close()
    #     db.close()

    # Mysql查询
    def mysql_select(self,query, db_config):
        conn = pymysql.connect(**db_config)
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        cursor.execute(query)
        result = cursor.fetchall()
        cursor.close()
        conn.close()
        return result  # 数据库取出是一个list此处直接加个下标

    # 多条
    def mysql_selects(self,query_list, db_config):
        conn = pymysql.connect(**db_config)
        cursor = conn.cursor()
        for query in query_list:
            cursor.execute(query)
        result = cursor.fetchall()
        cursor.close()
        conn.close()
        return result[0]    # 数据库取出是一个list此处直接加个下标


    # 根据输入长度，生成随机字符串
    def random_str(self,length):
        # 定义数字、小写字母、大写字母的可选字符集
        digits = string.digits
        lowercase_letters = string.ascii_lowercase
        uppercase_letters = string.ascii_uppercase

        # 从每个字符集中随机选择一个字符，保证生成的字符串同时包含数字、小写字母、大写字母
        random_chars = [random.choice(digits), random.choice(lowercase_letters), random.choice(uppercase_letters)]

        # 从所有可选字符集中随机选择剩余的字符，保证生成的字符串包含数字、小写字母、大写字母，且长度为指定长度
        for i in range(length - 3):
            random_chars.append(random.choice(digits + lowercase_letters + uppercase_letters))

        # 将随机字符列表打乱，然后拼接成字符串返回
        random.shuffle(random_chars)
        return ''.join(random_chars)

    def random_num(self, num):
        return ''.join(random.sample(string.digits, num))

    # 主要用于测试用例中的动态参数关联字段及时间戳，暂时先这样实现，后续再看看有没有更好的办法
    def replace_testdata(self, d, old_value, new_value):
        if isinstance(d, list):
            for idx in range(len(d)):
                self.replace_testdata(d[idx], old_value, new_value)
        elif isinstance(d,dict):
            for k, v in d.items():
                if isinstance(v, dict):
                    self.replace_testdata(v, old_value, new_value)
                elif isinstance(v, list):
                    for idx in range(len(v)):
                        if isinstance(v[idx], dict):
                            self.replace_testdata(v[idx], old_value, new_value)
                        elif v[idx] == old_value:
                            v[idx] = new_value
                elif v == old_value:
                    d[k] = new_value
        else:
            d = new_value
        return d

    # 后续再优化这个替换方法
    def replace_testdata3(self, d, old_value, new_value):
        if isinstance(d, list):
            for idx in range(len(d)):
                self.replace_testdata3(d[idx], old_value, new_value)
        elif isinstance(d,dict):
            for k, v in d.items():
                if isinstance(v, dict):
                    self.replace_testdata3(v, old_value, new_value)
                elif isinstance(v, list):
                    for idx in range(len(v)):
                        if isinstance(v[idx], dict):
                            self.replace_testdata3(v[idx], old_value, new_value)
                        else:
                            v[idx] = v[idx].replace(old_value,new_value)
                else:
                    v = v.replace(old_value,new_value)
        else:
            d = d.replace(old_value,new_value)
        return d




if __name__ == '__main__':
    a = keyWords()
    Path = os.path.dirname(os.path.dirname(__file__))




